import router from '@/router'
import { defineStore } from 'pinia'
import type { Login, MenuData, State } from './index.d'

export default defineStore('home', {
	state: (): State => ({
		id: '',
		refresh: true,
		list: [],
		selectValue: [],
		collapsed: false,
		menuList: [],
		size: 15,
		backTopVisible: true,
		themeColor: '#7167e8',
		defaultPath: '',
		userInfo: {
			name: '',
			header: ''
		},
		pageTitle: ''
	}),
	// 添加异步action
	actions: {
		async fetchList() {
			this.list = await get({
				url: urls.fetchList,
				params: { page: 1, limit: 10, tab: 'share' }
			})
		},

		async fetchLogin() {
			const data = await post<Login>({ url: urls.fetchLogin })
			if (data.isLogin) {
				this.defaultPath = data.path
				this.userInfo = data.userInfo
				return Promise.resolve(data)
			} else {
				message.warning('您当前未登录呢')
				return Promise.reject()
			}
		},

		async initPage() {
			await this.fetchLogin()
			this.fetchMenu()
		},

		async fetchMenu() {
			const data = await post<MenuData>({ url: urls.fetchMenuList })
			this.menuList = data.sideBar || []
			this.selectValue = data.selectValue || []
			if (!this.id) {
				this.id = this.selectValue[0]?.value
			}
			if (this.refresh) router.replace({ path: this.defaultPath })
			this.refresh = false
		},

		handleIdChange(id: string) {
			this.id = id
			this.refresh = true
			router.replace('/')
			this.fetchMenu()
		}
	},
	persist: [
		{
			storage: window.localStorage,
			paths: ['size', 'backTopVisible', 'themeColor']
		},
		{
			storage: window.sessionStorage,
			paths: ['refresh', 'selectValue', 'id', 'menuList', 'defaultPath', 'userInfo']
		}
	]
})
